import os
import time
import traceback

from AtomClicker.app import atomic_actions
from AtomClicker.app.atomic_actions.screenshot_actions import take_screenshot
from AtomClicker.app.utils.logging_utils import logger
from AtomClicker.app.workflow.user_script_workflow import execute_user_script
from AtomClicker.config.config import PROCESS_DIR


class TaskWorkflowExecutor:
    """
    任务工作流执行器类
    """

    def __init__(self):
        """
        初始化方法
        """
        self.process_dir = self.create_dir()

    @staticmethod
    def create_dir():
        run_num = 1
        while True:
            run_dir = os.path.join(PROCESS_DIR, f'run{run_num}')
            if not os.path.exists(run_dir):
                os.makedirs(run_dir)
                break
            run_num += 1
        return os.path.join(run_dir)

    def take_screenshot(self, filename):
        file_path = os.path.join(self.process_dir, filename + '.png')
        return take_screenshot(file_path)

    def execute(self, task):
        """
        执行任务工作流，每个操作步骤都进行截图

        :param task: 任务
        :return: (执行结果, 错误信息)
        """
        try:
            # 获取原子操作列表
            atomic_action_list = execute_user_script(task)
            logger.info(f"开始任务: {task}")
            # 依次执行原子操作
            for index, step in enumerate(atomic_action_list):
                action_name = step['action']
                action_params = step['params']
                time.sleep(0.7)
                action_func = getattr(atomic_actions, action_name)
                action_func(action_params)
                self.take_screenshot(f"step{index + 1}_{action_name}")
                logger.info(f"第{index + 1}步: {action_name} 完成")
            return True, None
        except AttributeError as attr_err:
            logger.error(str(attr_err))
            return False, f"此操作未提供: {str(attr_err).split('has no attribute ')[-1]}"

        except Exception as general_err:
            logger.error("调用栈信息:\n%s", traceback.format_exc())
            return False, str(general_err)


# 示例用法
if __name__ == "__main__":
    TaskWorkflow = TaskWorkflowExecutor()
    task = "example_task"  # 示例任务
    result, error_info = TaskWorkflow.execute(task)
    if result:
        print("任务执行成功")
    else:
        print(f"任务执行失败，错误信息：{error_info}")
